package org.alino.core.utils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Desc fastjson 工具
 * @Author by Brant
 * @Date 2017/1/13
 */
public class JsonUtils {
    public static String toJson(Object o){
        return JSONObject.toJSONString(o);
    }
    public static String toJson(Object o,SerializeFilter serializeFilter){
        return JSONObject.toJSONString(o, serializeFilter);
    }
    public static String toJson(Object o,SerializeFilter... serializeFilter){
        return JSONObject.toJSONString(o, serializeFilter);
    }
    public static String toJson(Object o,SerializeFilter[] serializeFilter,SerializerFeature... features){
        return JSONObject.toJSONString(o, serializeFilter,features);
    }
    public static void write(HttpServletResponse response, Object o,SerializeFilter serializeFilter) throws IOException {
        responseProperty(response);
        write(response,toJson(o,serializeFilter));//,SerializerFeature.BrowserCompatible
    }
    public static void write(HttpServletResponse response, Object o,SerializeFilter... serializeFilter) throws IOException {
        responseProperty(response);
        write(response,toJson(o,serializeFilter));//,SerializerFeature.BrowserCompatible
    }
    public static void write(HttpServletResponse response, Object o) throws IOException {
        responseProperty(response);
        write(response,toJson(o));//,SerializerFeature.BrowserCompatible
    }
    private static void responseProperty(HttpServletResponse response){
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
    }
    private static void write(HttpServletResponse response,String result) throws IOException {
        response.getWriter().write(result);
        response.getWriter().flush();
        response.getWriter().close();
    }
}
